-- MagicMirrorM
-- created by cheny3
-- 魔镜

module("MagicMirrorM", package.seeall);

local magicMirrors = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    -- 转换下信息表
    local magic_mirror_CSV = get_magic_mirror_CSV();
    for i = 1, #magic_mirror_CSV do
        local row = magic_mirror_CSV[i];
        magicMirrors[row.id] = row;
    end

    magic_mirror_CSV = {};
end

-- 模块初始化
function init()
    loadCsv();

    EventMgr.removeAll("MagicMirrorM");
    -- 召唤兽
    EventMgr.register("MagicMirrorM",  event.CALL_SUMMON, function(args)
        local pos = args["pos"];
        tryKillSummon(pos);
    end);
end

-- 尝试杀死召唤的召唤兽
function tryKillSummon(pos)
    local mirrorPos = getMagicMirror("summon");
    if mirrorPos < 0 then
        trace("MagicMirrorM", "场上没有魔镜（召唤兽）");
        return;
    end

    local grid = DungeonM.getGridByPos(pos);
    local summon = grid.summon;
    if not summon or summon:isDead() then
        trace("MagicMirrorM", "位置：%d没有召唤兽或者已经死亡", pos);
        return;
    end

    -- 直接死亡
    summon:receiveDamage(summon:getHp());
    summon:die();

    -- 抛出事件
    EventMgr.fire(event.MAGIC_MIRROR_TRIGGER, {["type"] = "summon", ["pos"] = mirrorPos});
end

-- 检索
function query(classId, path)
    local m = magicMirrors[classId];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 场上魔镜位置(某个类型)
function getMagicMirror(rule)
    local pos = -1;
    for index = 1, GRID_SIZE do
        local grid = DungeonM.getGridByPos(index);
        if grid.type == GRID_TYPE_MAGIC_MIRROR
            and query(grid.mirror_id, "rule") == rule then
            pos = grid:getPos();
            break;
        end
    end

    return pos;
end

